<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      :btnList="fullInfo.btnList"
    >
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <basic-information :info="infoList"></basic-information>
        </div>
      </div>

      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('detailInfo') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <page-filter
            v-model:query="filterInfo.query"
            :filter-list="filterInfo.list"
          >
            <template v-slot:filter-receivingCodeScan>
              <input
                type="password"
                show-password
                autocomplete="off"
                auto-complete="off"
                readonly
                @focus="onFocusInputScan"
                class="inputRefScanHidden"
                v-bind:class="{ active: isActive }"
              />
              <el-input
                class="inputScan"
                ref="inputRefScan"
                placeholder="请扫码或输入条码"
                @keydown.enter.native="scanCode"
                v-model="filterInfo.scanInfo.code"
                @input="(e) => (filterInfo.scanInfo.code = validSe(e))"
                @blur="onBlurInputScan"
                :clearable="true"
              >
                <template #prepend>产品条码</template>
              </el-input>
            </template>
          </page-filter>
          <div class="flex_full_item">
            <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :api="getExportDetailAll"
                :query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                @handleEvent="handleEvent"
                :spanMethod="objectSpanMethod"
              >
                <template v-slot:col-licenseNumber="scope">
                  <p>{{ scope.row.licenseNumber || '-' }}</p>
                  <p>{{ scope.row.brandName || '-' }}</p>
                </template>
                <template v-slot:col-commonName="scope">
                  <p>{{ scope.row.commonName || '-' }}</p>
                  <p>{{ scope.row.productCode || '-' }}</p>
                  <p>{{ scope.row.alias || '-' }}</p>
                </template>
                <template v-slot:col-type="scope">
                  <p>{{ scope.row.productTypeValue || '-' }}</p>
                  <p>{{ scope.row.codeTypeValue || '-' }}</p>
                  <p>{{ scope.row.productCategoryValue || '-' }}</p>
                </template>
                <template v-slot:col-standard="scope">
                  <p>{{ scope.row.standard || '-' }}</p>
                  <p>{{ scope.row.unitName || '-' }}</p>
                </template>
              </page-table>
            </el-form>
          </div>
        </div>
      </div>
    </NewFullScreen>
    <select-product
      :query="productInfo.query"
      v-if="productInfo.visible"
      @callback="selectProduct"
      v-model:showDialog="productInfo.visible"
    />
    <!-- <SelectDepotStorage
            :query="depotStorageInfo.query"
            v-if="depotStorageInfo.visible"
            @callback="fillStorageProduct"
            v-model:showDialog="depotStorageInfo.visible"
          /> -->
    <select-batch-number
      :query="batchNumberInfo.query"
      v-if="batchNumberInfo.visible"
      @callback="selectBatchNumberBack"
      v-model:showDialog="batchNumberInfo.visible"
    />
    <select-individual
      v-if="individualInfo.visible"
      v-model:show-dialog="individualInfo.visible"
      :query="individualInfo.query"
      :info="individualInfo.productInfo"
      @callback="selectedProductDetails"
    />
  </div>
</template>

<script setup name="useReturnApplicationExport">
import {
  getUseApplication,
  getExportDetailAll,
  createUseExport,
  exportUseApplication,
  printUseApplication,
} from '@/api/use.js'
import { getDepotStorageAll } from '@/api/stock.js'
import selectIndividual from './selectIndividual/index'

const { proxy } = getCurrentInstance()
const emit = defineEmits()

const props = defineProps(['visible', 'title', 'id'])

const index = ref('')
const pos = ref('')
const productIds = ref([])
const spanArr = ref('')
const selectRows = ref([])
const storageData = ref([])
const chooseIndex = ref([])
const totalRows = ref([])
const isActive = ref(false)
const infoList = reactive({
  data: {},
  fieldList: [
    { label: '出库单号', value: 'orderNo', type: 'text' },
    { label: '退回人', value: 'createUserName', type: 'text' },
    { label: '退出部门', value: 'sourceDeptName', type: 'text' },
    { label: '退回部门', value: 'deptName', type: 'text' },
    { label: '退入仓库', value: 'storageDepotName', type: 'text' },
    { label: '退出仓库', value: 'exportDepotName', type: 'text' },
  ],
})
// 过滤相关配置
const filterInfo = reactive({
  query: {
    statusNotIn: 'complete', //已完成的过滤
    useApplicationId: '',
  },
  scanInfo: {
    code: '',
  },
  list: [
    { type: 'button', label: '添加产品', event: addProduct },
    { type: 'button', label: '删除', event: deleteCheck },
    { type: 'slot', value: 'receivingCodeScan' },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  data: [],
  fieldList: [
    {
      label: '通用名称\n编码\n别名',
      value: 'commonName',
      minWidth: '220px',
      type: 'slot',
    },
    {
      label: '产品类型\n条码类型\n产品分类',
      value: 'type',
      minWidth: '150px',
      type: 'slot',
    },
    { label: '规格\n计量单位', value: 'standard', type: 'slot' },
    {
      label: '领出仓库存量',
      value: 'totalStockQty',
      type: 'column',
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      label: '申请数量',
      value: 'qty',
      type: 'column',
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      label: '退出数量',
      value: 'exportQty',
      type: 'column',
      formatter: proxy.$fn.qtyFormatter,
    },
    { label: '生产批号', value: 'batchNumber' },
    { label: '生产日期', value: 'productionDate' },
    { label: '失效日期', value: 'validityDate' },
    {
      label: '证号\n生产厂家',
      value: 'licenseNumber',
      minWidth: '220px',
      type: 'slot',
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '150',
    btList: [
      {
        label: '添加批号',
        event: selectBatchNumber,
        show: true,
      },
      {
        label: '选择个体',
        event: _selectIndividual,
        show: true,
      },
      { label: '删除', event: deleteOne, show: true },
    ],
  },
})
const fullInfo = reactive({
  btnList: [
    { label: '提交', event: _export, show: true },
    { label: '导出excel', event: exportExcel, show: false },
    { label: '打印', event: print, show: false },
  ],
})
//选择产品相关
let productInfo = reactive({
  visible: false,
  query: {},
})
// //选择库存产品
const depotStorageInfo = reactive({
  //   visible: false,
  //   query: {},
  //   //当前选择的序号值
  currentIndex: null,
})
const batchNumberInfo = reactive({
  visible: false,
  query: {},
})
const individualInfo = reactive({
  visible: false,
  query: {},
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})

watch(
  () => props.visible,
  (value) => {
    showDialog.value = value
  },
  {
    immediate: true,
  }
)
watch(
  () => tableInfo.data,
  () => {
    getSpanArr(tableInfo.data)
  }
)

onMounted(() => {
  getList()
})

function getList() {
  getUseApplication(props.id).then((res) => {
    if (res.success) {
      infoList.data = res.data
    }
  })
  filterInfo.query.useApplicationId = props.id
  tableInfo.refresh = Math.random()
}
// 触发事件
function handleEvent(event, data) {
  if (event === 'list') {
    productIds.value = data.map(function (item) {
      return item.productId
    })
    totalRows.value = Object.assign([], tableInfo.data) //用于删除后，再添加限行
  }
  switch (event) {
    case 'tableCheck':
      selectRows.value = data
      filterInfo.list[1].disabled = !selectRows.value.length
      break
  }
}
function addProduct() {
  productInfo.visible = true
  const idNotIn = tableInfo.data.map(function (item) {
    return item.productId
  })
  let diff = productIds.value.filter(function (val) {
    return idNotIn.indexOf(val) === -1
  })
  if (diff.length > 0) {
    productInfo.query.idIn = diff.join(',')
  } else {
    productInfo.query.idIn = '-1' //确保查不出数据来
  }
}
// 删除
function deleteOne(row, index) {
  tableInfo.data.splice(index, 1)
}
function deleteCheck() {
  if (selectRows.value && selectRows.value.length != 0) {
    tableInfo.data = tableInfo.data.filter(
      (row) => !selectRows.value.includes(row)
    )
  } else {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '请至少选择一条操作数据',
    })
  }
}
function selectProduct(rows) {
  if (rows) {
    rows.forEach((item) => {
      let index = totalRows.value.findIndex((a) => a.productId === item.id)
      if (index != -1) {
        item.totalStockQty = totalRows.value[index].totalStockQty
        item.qty = totalRows.value[index].qty
        item.batchNumber = totalRows.value[index].batchNumber
        item.productionDate = totalRows.value[index].productionDate
        item.validityDate = totalRows.value[index].validityDate
      }
      item.productId = item.id
      item.id = null
      item.productCode = item.code
      item.productTypeValue = item.typeValue
    })
    tableInfo.data.push(...rows)
  }
}
//增加相同产品+批号 数量
function increaseSameProductNumber(rows) {
  if (rows && rows.length != 0) {
    rows.forEach((row) => {
      tableInfo.data.some((item, i) => {
        if (
          item.productCode == row.productCode &&
          item.batchNumber === row.batchNumber
        ) {
          item.exportQty = item.exportQty === undefined ? 1 : item.exportQty + 1
          rows.splice(i, 1)
          return true
        }
      })
    })
  }
}
//填充库存产品
function fillStorageProduct(row) {
  increaseSameProductNumber(row)
  let arr = tableInfo.data.slice(0)
  let data = arr[depotStorageInfo.currentIndex]
  let newData = []
  if (row.length) {
    row.forEach((item) => {
      let addData = {
        batchNumber: item.batchNumber,
        productionDate: item.productionDate,
        validityDate: item.validityDate,
        price: item.price,
        code: item.code,
        depotStorageId: item.id,
        exportQty: 1,
      }
      newData.push({ ...data, ...addData })
    })
  }
  newData.unshift(depotStorageInfo.currentIndex + 1, 0)
  ;[].splice.apply(arr, newData)
  if (!data.hasOwnProperty('batchNumber') && !data.batchNumber) {
    arr.splice(depotStorageInfo.currentIndex, 1)
  }
  tableInfo.data = arr
}
function getSpanArr(data) {
  spanArr.value = []
  for (let i = 0; i < data.length; i++) {
    if (i === 0) {
      spanArr.value.push(1)
      pos.value = 0
    } else {
      if (data[i].productCode === data[i - 1].productCode) {
        spanArr.value[pos.value] += 1
        spanArr.value.push(0)
      } else {
        spanArr.value.push(1)
        pos.value = i
      }
    }
  }
}
function _export() {
  let type = 'create'
  let api = createUseExport
  if (tableInfo.data.length === 0) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '出库明细不能为空',
    })
    return
  } else {
    const qtyZero = tableInfo.data.filter((item) => item.exportQty > 0)
    if (!qtyZero.length) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '出库数量不能全为0',
      })
      return
    }
    let totalStockQtyName = tableInfo.data
      .filter(
        (item) => item.exportQty > item.totalStockQty && item.exportQty > 0
      )
      .map((item) => item.commonName)
    if (totalStockQtyName.length) {
      proxy.$alert(`产品【${totalStockQtyName}】库存不足`, '操作提示', {
        confirmButtonText: '确定',
      })
      return
    }
    let qtyName = tableInfo.data
      .filter((item) => {
        if (item.exportQty > 0) {
          if (item.totalStockQty > item.qty) {
            return item.qty < item.exportQty
          } else {
            return item.totalStockQty < item.exportQty
          }
        }
      })
      .map((item) => item.commonName)
    if (qtyName.length) {
      proxy.$alert(`产品【${qtyName}】退出数量多了`, '操作提示', {
        confirmButtonText: '确定',
      })
      return
    }
    let data = {
      useExport: {
        ...infoList.data,
        useApplicationId: infoList.data.id,
        type: 'useReturn',
      },
      useExportDetails: tableInfo.data,
    }
    proxy.$handleAPI(type, api, data).then((res) => {
      if (res.success) {
        showDialog.value = false
        emit('callback', null)
      }
    })
  }
}
function objectSpanMethod({ row, column, rowIndex, columnIndex }) {
  // console.log( spanArr.value, rowIndex, columnIndex)
  if (columnIndex >= 1 && columnIndex <= 4) {
    const _row = spanArr.value[rowIndex]
    const _col = _row > 0 ? 1 : 0
    return {
      rowspan: _row,
      colspan: _col,
    }
  }
}
function selectBatchNumber(row, index) {
  //添加批号
  index.value = index
  const depotStorageIdNotIn = tableInfo.data
    .filter((value) => value.productId === row.productId && value.batchNumber)
    .map((value) => value.depotStorageId)
  batchNumberInfo.visible = true
  batchNumberInfo.query = {
    depotId: infoList.data.exportDepotId,
    productId: row.productId,
    idNotIn: depotStorageIdNotIn.length ? depotStorageIdNotIn.toString() : '',
  }
}
function selectBatchNumberBack(data) {
  //批号回调
  if (data.length) {
    // let arr = _.differenceBy(data, tableInfo.data, 'batchNumber')
    let arr = data
    if (arr.length) {
      arr.forEach((item) => {
        index.value += 1
        let i = _.findIndex(tableInfo.data, function (o) {
          return o.productId === item.productId && !o.batchNumber
        })
        if (i >= 0) {
          tableInfo.data[i] = {
            ...tableInfo.data[i],
            id: null,
            batchNumber: item.batchNumber,
            productionDate: item.productionDate,
            validityDate: item.validityDate,
            depotStorageId: item.id,
            totalStockQty: item.stockQty,
          }
        } else {
          let i = _.findIndex(tableInfo.data, function (o) {
            return (
              o.productId === item.productId &&
              item.batchNumber + item.productionDate + item.validityDate !==
                o.batchNumber + o.productionDate + o.validityDate
            )
          })
          if (i >= 0) {
            let data = {
              ...tableInfo.data[i],
              id: null,
              batchNumber: item.batchNumber,
              productionDate: item.productionDate,
              validityDate: item.validityDate,
              depotStorageId: item.id,
              totalStockQty: item.stockQty,
              price: item.price,
            }
            tableInfo.data.splice(i + 1, 0, data)
          }
        }
      })
    }
  }
}
function _selectIndividual(data) {
  //选择个体
  if (!data.batchNumber && data.codeType !== 'none') {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: `请添加产品【${data.commonName}】的批号`,
    })
    return
  }
  const params = {
    stockQtyGreater: 0,
    codeType: data.codeType,
    depotStorageId: data.depotStorageId,
  }
  individualInfo.visible = true
  individualInfo.query = params
  individualInfo.productInfo = data
}
function selectedProductDetails(data) {
  //个体返回
  tableInfo.data.forEach((row, index) => {
    if (
      data.depotStorageId === row.depotStorageId &&
      row.productId === data.productId
    ) {
      tableInfo.data[index]['exportQty'] = data.exportQty
      row.detailExtVOS = data.details
    }
  })
}
//扫码出库
function onFocusInputScan() {
  setTimeout(() => {
    proxy.$refs.inputRefScan.focus()
    isActive.value = true
    document
      .getElementsByClassName('inputRefScanHidden')[0]
      .removeAttribute('readonly')
  }, 300)
}
function onBlurInputScan() {
  isActive.value = false
}
function scanCode() {
  let code = event.target.value || undefined
  if (!code) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '请扫描二维码',
    })
    return
  }
  proxy.$refs.inputRefScan.value = code
  let query = {
    depotId: infoList.data.exportDepotId,
    code: encodeURIComponent(filterInfo.scanInfo.code),
  }
  getDepotStorageAll(query).then((res) => {
    if (res.success) {
      if (res.data.length) {
        var addData = res.data[0]
        //查找存在的数据
        var find = false
        tableInfo.data.some((item, i) => {
          if (item.productCode === addData.productCode) {
            depotStorageInfo.currentIndex = i
            find = true
            return true
          }
        })
        if (find) {
          fillStorageProduct([addData])
        } else {
          proxy.$message({
            duration: 3500,
            type: 'warning',
            showClose: true,
            message: '当前扫码编号【' + query.code + '】不属于本次领用产品',
          })
        }
      } else {
        proxy.$message({
          duration: 3500,
          type: 'warning',
          showClose: true,
          message: '当前扫码编号【' + query.code + '】不在领用仓库',
        })
      }
      filterInfo.scanInfo.code = ''
    }
  })
}
//导出excel
function exportExcel() {
  exportUseApplication(infoList.data.id).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
//打印
function print() {
  printUseApplication(infoList.data.id).then((resp) => {
    if (resp && resp.success) {
      proxy.$print.printOrder(resp.data)
    }
  })
}
</script>

<style scoped>
.inputRefScanHidden {
  position: absolute;
  color: transparent;
  background-color: transparent;
  caret-color: black;
  border: none;
  outline: none;
  height: 30px;
  margin-left: 115px;
  width: 200px;
  z-index: 12;
}
.inputScan {
  ime-mode: disabled;
}
.active {
  display: none;
}
</style>
